package com.heima.test7;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;


/**
 * 服务器端接收上传文件
 */
public class UploadServer {
    public static void main(String[] args) throws IOException {
        //1.创建服务器端对象
        ServerSocket ss = new ServerSocket(1000);

        while (true) {
            // 2 等待连接
            Socket accept = ss.accept();
            System.out.println("收到来自：" + accept.getRemoteSocketAddress());

            //创建子线程处理任务
            new Thread(new MyRunnable(accept)).start();
        }
    }
}

class MyRunnable implements Runnable {

    Socket accept;

    public MyRunnable(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        try {
            //把接收到客户端的文件写到硬盘里面，用uuid随机生成一个文件名
            //创建文件输出流对象 用来保存上传来的文件
            FileOutputStream fos = new FileOutputStream("D:\\heima\\project2\\exam\\upload\\" + UUID.randomUUID());

            //3 接收客户端发来的数据
            InputStream is = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = is.read(bytes)) != -1) {//等待
                fos.write(bytes, 0, len);
            }
            //5 获取网络输出流 给客户端回复一个  上传成功
            OutputStream os = accept.getOutputStream();
            os.write("呵呵".getBytes());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
